# coding=utf-8
import MySQLdb
import MySQLdb.cursors
import configSetting
from DBUtils.PooledDB import PooledDB


def ping(origin_func):
    def wrapper(self, *args, **kwargs):
        try:
            self.restart_conn()
            u = origin_func(self, *args, **kwargs)
            self.close()
            return u
        except Exception as e:
            self.restart_conn()
            return e
    return wrapper


class DbManager:
    __pool = None

    def __init__(self):
        # 启动时连接池中创建的的连接数
        self.mincached = 5
        # 连接池中最大允许创建的连接数
        self.maxcached = 20
        self.conn_args = {'host': configSetting.mysql_host,
                      'port': configSetting.mysql_port,
                      'db': configSetting.mysql_db,
                      'user': configSetting.mysql_user,
                      'passwd': configSetting.mysql_pwd,
                     'charset': 'utf8',
                     'cursorclass': MySQLdb.cursors.DictCursor,
                          'mincached': 5,
                          'maxcached': 20
                     }
        self.conn = DbManager.getConn(self.conn_args)
        self.cursor = self.conn.cursor()

    @staticmethod
    def getConn(conn_args):
        #静态方法，从连接池中取出连接
        if DbManager.__pool is None:
            __pool = PooledDB(MySQLdb, **conn_args)
            conn = __pool.connection()
            cursor = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)
            cursor.execute("set names utf8mb4;")
            cursor.close()
        return __pool.connection()

    def restart_conn(self):
        try:
            self.conn.ping()
        except Exception as e:
            print(e)
            self.conn = DbManager.getConn(self.conn_args)
            self.cursor = self.conn.cursor()

    @ping
    def execute(self, sql, commit=False, param=None):
        """ sql语句"""
        self.cursor = self.conn.cursor()
        rows = self.cursor.execute(sql, param)
        if commit:
            self.conn.commit()

        return rows

    @ping
    def query_one(self, sql, param=None):
        """ 获取一条信息 """
        self.cursor = self.conn.cursor()
        rowcount = self.cursor.execute(sql, param)
        if rowcount > 0:
            res = self.cursor.fetchone()
        else:
            res = None
        return res

    @ping
    def query_all(self, sql, param=None):
        """ 获取所有信息 """
        self.cursor = self.conn.cursor()
        rowcount = self.cursor.execute(sql, param)
        if rowcount > 0:
            res = self.cursor.fetchall()
        else:
            res = []
        return res

    def close(self):
        self.cursor.close()


conn = DbManager()
if __name__ == "__main__":
    sql = f"select S_COMPANYCODE from FOF_FUNDINFO where S_FUNDCODE={fundId}"
    ret = conn.query_one(sql)
    S_COMPANYCODE = ret['S_COMPANYCODE']
    print(ret)
